package com;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;

//   $2a$10$AT6WLF7easYhLh7WmfIkE.k0LaEK9iJBizhOtrAZL//Ymjw/pTnVe
public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    private  BCryptPasswordEncoder encoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {



        //从数据库查询用户 为空的话 返回null
        User userDb = findUserByUname(username);
        if (userDb==null){
            return null;

        }

        //获取密码
        String password = userDb.getPassword();



        //添加权限
        ArrayList<GrantedAuthority> grantedAuthorityArrayList = new ArrayList();
        grantedAuthorityArrayList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        grantedAuthorityArrayList.add(new SimpleGrantedAuthority("delete"));
        grantedAuthorityArrayList.add(new SimpleGrantedAuthority("add"));

        //返回
        return new org.springframework.security.core.userdetails.User(username,password,grantedAuthorityArrayList);


    }

    //模拟从数据库查询
    private User findUserByUname(String username) {
        if ("admin".equals(username)) {
            User user = new User();
            user.setUsername(username);
            String encode = encoder.encode("123456");
            System.out.println(encode);
            user.setPassword(encode);
            return user;
        }
        return null;
    }
}
